<?php

namespace System\Data\Drivers\MySQLi
{

    /**
     * MySQLi Driver Connection
     */
    class Driver extends \System\Types\Object implements \System\Data\IDataDriver
    {

        /**
         * @var \System\Data\IDataDriver
         */
        private static $_instance;

        /**
         * @var \mysqli
         */
        private $_connection;

        function __construct(\System\Core\ConfigItems $items = null)
        {
            if (!$items)
                $items = \System\Core\Config::Get(\CFG_DATABASE);

            $this->Connect($items);
        }

        /**
         * @return \System\Data\IDataDriver
         */
        public static function &GetInstance()
        {
            if (!self::$_instance)
                self::$_instance = new self();

            return self::$_instance;
        }

        /**
         * @return boolean
         */
        public function Connect(\System\Core\ConfigItems $items)
        {
            $this->_connection = new \mysqli($items->Get('host')->Valor, $items->Get('user')->Valor, $items->Get('pass')->Valor, $items->Get('base')->Valor);

            if (\mysqli_connect_errno())
            {
                \System\Core\Errors\Error::ShowErr("#" . \mysqli_connect_errno() . ": " . \mysqli_connect_error());
                return false;
            }

            return true;
        }

        /**
         * @return boolean
         */
        public function Dispose()
        {
            return $this->_connection->close();
            static::$_instance = null;
        }

        private function parse(\System\Types\String &$sql, Array &$values)
        {
            $_sql = $sql->ToString();

            for ($i = 0; $i < count($values); $i++)
            {
                $_sql = \str_replace("{{$i}}", $this->_connection->real_escape_string($values[$i]->ToString()), $_sql);
            }

            return $_sql;
        }

        /**
         * @return IDataResult
         */
        public function Run(\System\Types\String $sql, Array $values = array())
        {
            $sqlQuery = $this->parse($sql, $values);

            $query = $this->_connection->query($sqlQuery);

            return \is_bool($query) ? $query : new \System\Data\Drivers\MySQLi\Result($query, $this);
        }

        /**
         * @return boolean
         */
        public function SelectDatabase(\System\Types\String $base, \System\Types\String $user = null, \System\Types\String $pass = null)
        {
            if ($user)
                return $this->_connection->change_user($user->ToString(), $pass->ToString(), $base->ToString());

            return $this->_connection->select_db($base->ToString());
        }

    }

}
